package services

import (
	"errors"
	"fmt"
	"haili/common"
	"haili/models"
	"regexp"
)

type UserService struct{}

var userModel models.UserModel

func (UserService) GetUsers(params map[string]interface{}) []models.User {
	return userModel.Find(params)
}
func (UserService) GetUser(user *models.User) (bool, error) {
	user.PassWord = common.EncodePassWord(user.PassWord)
	s, e := userModel.Select(user)
	if nil != e {
		return s, fmt.Errorf("查询用户失败 %s", e.Error())
	}
	return s, nil
}

// AddUser func
func (UserService) AddUser(user *models.User) error {
	//新增用户
	user.PassWord = common.EncodePassWord(user.PassWord)
	err := userModel.Insert(user)
	if nil != err {
		return fmt.Errorf("新增用户失败%s", err.Error())
	}
	return nil
}

func (UserService) CheckPhone(user *models.User) (bool, error) {
	reg := regexp.MustCompile(`^1(3|4|5|7|8)\d{9}$`)
	isPhone := reg.MatchString(user.Phone)
	if !isPhone {
		return false, errors.New("请输入正确的手机号")
	}

	user.PassWord = "" //只验证手机号
	s, e := userModel.Select(user)
	if nil != e {
		return false, fmt.Errorf("注册失败 %s", e.Error())
	}
	if !s {
		return true, nil
	}
	return false, errors.New(user.Phone + "已被注册")
}

//修改用户信息
func (UserService) UpdateUser(user models.User) error {
	if "" != user.PassWord {
		user.PassWord = common.EncodePassWord(user.PassWord)
	}
	_, err := userModel.Update(user)
	if nil != err {
		return fmt.Errorf("修改用户失败", err.Error())
	}
	return nil
}
